package miiteen.hb.webservice.util;

import miiteen.hb.webservice.beans.FileInfoResponse;
import miiteen.hb.webservice.beans.FileListResponse;
import miiteen.hb.webservice.beans.Response;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.List;

public class ResponseUtil {
    /**
     * 解析webservice返回值
     *
     * @param xmlStr
     * @return
     * @throws DocumentException
     */
    public static Response toResponse(String xmlStr) throws DocumentException {
        //将xml格式的字符串转换成Document对象
        Document doc = DocumentHelper.parseText(xmlStr);
        //获取根节点
        Element root = doc.getRootElement();
        //获取主体节点
        Element ResponseCode = root.element("ResponseCode");
        Element ResponseNote = root.element("ResponseNote");
        Element ResponseData = root.element("ResponseData");
        //返回Response对象
        Response response = new Response();
        response.setResponseCode(Integer.parseInt(ResponseCode.getTextTrim()));
        response.setResponseNote(ResponseNote.getTextTrim());
        response.setResponseData(ResponseData);
        return response;
    }

    /**
     * 文件列表数据转换
     *
     * @param xmlStr
     * @return
     * @throws DocumentException
     */
    public static FileListResponse toFileListResponse(String xmlStr) throws DocumentException {
        FileListResponse result = new FileListResponse();
        //解析响应结果
        Response response = toResponse(xmlStr);
        //解析响应内容
        if (response.getResponseCode() == 0) {
            Element root = response.getResponseData();
            //解析文件列表
            Element elementList = root.element("CommonFileListConverter");
            List<Element> items = elementList.elements("Item");
            List<FileInfoResponse> list = new ArrayList<>();
            for (Element item : items) {
                //转换FileResponse
                FileInfoResponse fileInfoResponse = (FileInfoResponse) XmlUtil.xmlStrToBean(item, FileInfoResponse.class);
                list.add(fileInfoResponse);
            }
            result.setList(list);
            //解析总条数
            Element totalCount = root.element("TotalCount");
            result.setTotalCount(Integer.parseInt(totalCount.getTextTrim()));
        }
        return result;
    }
}
